#!/usr/bin/python3
# coding=utf-8
# 回放csv录制内容
import win32gui, win32ui, win32con, win32api
def capture_window(title=u"无标题 - 记事本", fname="a.bmp", in_hwnd = None):
    '''
    获取坐标，函数原型是
    BOOL GetWindowRect(
        HWND   hWnd,
        LPRECT lpRect
    );
    但python里将输入参数做了修改
    '''
    print("write ", fname)
    if in_hwnd:
        hwnd = in_hwnd
    else:
        hwnd = win32gui.FindWindow(0, title)
        # hwnd = win32gui.FindWindow(0, title)
        if 0 == hwnd:
            print("窗口不存在")
            return ;
    win32gui.ShowWindow(hwnd, True)


    rect = win32gui.GetWindowRect(hwnd)
    # 根据窗口句柄获取窗口的设备上下文DC（Divice Context）
    hwndDC = win32gui.GetWindowDC(hwnd)
    # 根据窗口的DC获取mfcDC
    mfcDC = win32ui.CreateDCFromHandle(hwndDC)
    # mfcDC创建可兼容的DC
    saveDC = mfcDC.CreateCompatibleDC()
    # 创建bigmap准备保存图片
    saveBitMap = win32ui.CreateBitmap()
    # 获取监控器信息
    # MoniterDev = win32api.EnumDisplayMonitors(None, None)
    rect = win32gui.GetWindowRect(hwnd)
    # x, y = win32gui.ScreenToClient(hwnd, (rect[0], rect[1]))
    # [x, y, h, w] = rect
    h = rect[3] - rect[1];
    w = rect[2] - rect[0];
    
    
    print(rect, h, w)
    # print w,h　　　#图片大小
    # 为bitmap开辟空间
    saveBitMap.CreateCompatibleBitmap(mfcDC, w, h)
    # 高度saveDC，将截图保存到saveBitmap中
    saveDC.SelectObject(saveBitMap)
    # 截取从左上角（0，0）长宽为（w，h）的图片
    saveDC.BitBlt((0, 0), (w, h), mfcDC, (0, 0), win32con.SRCCOPY)
    saveBitMap.SaveBitmapFile(saveDC, fname)
